import 'dart:io';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hinge/common/index.dart';
import 'package:hinge/common/widgets/custom_dialog.dart';
import 'package:hinge/pages/recommend/recommend_page.dart';
import 'package:hinge/store/root_store.dart';
import 'package:mobx/mobx.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart'
    show EnglishAssetPickerTextDelegate;
import 'package:hinge/common/utils/sp_util.dart';
import 'package:hinge/common/services/topic_comment_service.dart';

part 'setup_store.g.dart';

class SetupStore = _SetupStore with _$SetupStore;

abstract class _SetupStore with Store {
  @observable
  bool isLoading = false;

  @observable
  UserModel? currentUser;

  @observable
  bool isGuest = false;

  // 初始化方法，获取当前用户信息
  @action
  Future<void> init() async {
    isLoading = true;
    try {
      currentUser = UserService.getCurrentUser();
      isGuest = UserService.isGuestUser();
    } catch (e) {
      print('Error initializing setup store: $e');
    } finally {
      isLoading = false;
    }
  }

  // 修改个人签名
  @action
  Future<bool> updateSignature(String newSignature) async {
    if (currentUser == null) return false;

    isLoading = true;
    bool result = false;

    try {
      result = await UserService.updateUser(
        id: currentUser!.id,
        description: newSignature,
      );

      if (result) {
        // 更新成功，重新获取用户信息
        currentUser = UserService.getUserById(currentUser!.id);
      }
    } catch (e) {
      print('Error updating signature: $e');
    } finally {
      isLoading = false;
    }

    return result;
  }

  // 退出登录
  @action
  Future<void> logout() async {
    isLoading = true;
    try {
      await UserService.logout();
      // 登出后自动创建游客账号
      await UserService.createGuestUser();
      currentUser = UserService.getCurrentUser();
      isGuest = true;

      // 通知所有观察者数据已更新
      notifyUserDataChanged();
    } catch (e) {
      print('Error logging out: $e');
    } finally {
      isLoading = false;
    }
  }

  // 删除账号
  @action
  Future<bool> deleteAccount() async {
    if (currentUser == null || isGuest) return false;

    isLoading = true;
    bool result = false;

    try {
      // 删除用户
      result = await UserService.deleteUser(currentUser!.id);

      if (result) {
        // 删除成功后登出
        await UserService.logout();
        // 创建游客账号
        await UserService.createGuestUser();
        currentUser = UserService.getCurrentUser();
        isGuest = true;

        // 通知所有观察者数据已更新
        notifyUserDataChanged();
      }
    } catch (e) {
      print('Error deleting account: $e');
    } finally {
      isLoading = false;
    }

    return result;
  }

  // 显示退出登录确认对话框
  void showLogoutConfirmDialog(BuildContext context) {
    CustomDialog.show(
      context: context,
      title: 'Log Out',
      content: 'Are you sure you want to log out?',
      cancelText: 'Cancel',
      confirmText: 'Log Out',
      onConfirm: () async {
        // 先退出登录
        await logout();

        // 刷新状态
        notifyUserDataChanged();

        // 显示退出成功提示
        EasyLoading.showSuccess('Log out successfully');

        // 返回首页
        context.go('/');

        // 延迟一点时间确保路由已完成，然后再次刷新状态
        Future.delayed(Duration(milliseconds: 500), () {
          // 再次刷新状态，使用 getter 替代直接创建实例
          RootStore().recommendStore.refreshPerfumeData();

          // 通过全局Key强制刷新RecommendPage
          final state = RecommendPage.globalKey.currentState;
          if (state != null) {
            state.forceRefresh();
          }
        });
      },
    );
  }

  // 显示删除账号确认对话框
  void showDeleteAccountConfirmDialog(BuildContext context) {
    CustomDialog.show(
      context: context,
      title: 'Delete Account',
      content:
          'Are you sure you want to delete your account? This action cannot be undone.',
      cancelText: 'Cancel',
      confirmText: 'Delete',
      onConfirm: () async {
        final result = await deleteAccount();
        if (result) {
          context.go('/');
        }
      },
    );
  }

  // 显示需要登录的对话框
  void showLoginRequiredDialog(BuildContext context, String actionName) {
    CustomDialog.show(
      context: context,
      title: 'Login Required',
      content: 'You need to login to $actionName. Would you like to login now?',
      cancelText: 'Cancel',
      confirmText: 'Login',
      onConfirm: () {
        context.push('/login');
      },
    );
  }

  // 更新用户昵称
  @action
  Future<bool> updateUserNickname(String nickname) async {
    if (currentUser == null) return false;

    isLoading = true;
    bool result = false;

    try {
      result = await UserService.updateUser(
        id: currentUser!.id,
        nickname: nickname,
      );

      if (result) {
        // 更新成功，重新获取用户信息
        currentUser = UserService.getUserById(currentUser!.id);
        // 同时更新当前登录用户的缓存
        await UserService.setCurrentUser(currentUser!);

        // 强制刷新所有相关的观察者
        notifyUserDataChanged();
      }
    } catch (e) {
      print('Error updating nickname: $e');
    } finally {
      isLoading = false;
    }

    return result;
  }

  // 更新用户描述
  @action
  Future<bool> updateUserDescription(String description) async {
    if (currentUser == null) return false;

    isLoading = true;
    bool result = false;

    try {
      result = await UserService.updateUser(
        id: currentUser!.id,
        description: description,
      );

      if (result) {
        // 更新成功，重新获取用户信息
        currentUser = UserService.getUserById(currentUser!.id);
        // 同时更新当前登录用户的缓存
        await UserService.setCurrentUser(currentUser!);

        // 强制刷新所有相关的观察者
        notifyUserDataChanged();
      }
    } catch (e) {
      print('Error updating description: $e');
    } finally {
      isLoading = false;
    }

    return result;
  }

  // 更新用户头像
  @action
  Future<bool> updateUserAvatar(String avatar) async {
    if (currentUser == null) return false;

    isLoading = true;
    bool result = false;

    try {
      result = await UserService.updateUser(
        id: currentUser!.id,
        avatar: avatar,
      );

      if (result) {
        // 更新成功，重新获取用户信息
        currentUser = UserService.getUserById(currentUser!.id);
        // 同时更新当前登录用户的缓存
        await UserService.setCurrentUser(currentUser!);

        // 强制刷新所有相关的观察者
        notifyUserDataChanged();

        // 清除话题数据缓存，确保下次打开话题页面时能获取最新的用户信息
        // 这样用户修改头像后，在话题评论中也能看到最新的头像
        final topicComments = TopicCommentService.getAllComments();
        final userId = currentUser!.id;

        // 更新所有由该用户发表的评论中的用户信息
        final updatedComments =
            topicComments.map((comment) {
              if (comment.userId == userId) {
                return comment.copyWith(user: currentUser);
              }
              return comment;
            }).toList();

        // 保存更新后的评论
        await SpUtil.setModelList(
          'app_topic_comments',
          updatedComments.map((comment) => comment.toJson()).toList(),
        );
      }
    } catch (e) {
      print('Error updating avatar: $e');
    } finally {
      isLoading = false;
    }

    return result;
  }

  // 通知用户数据已更新
  @action
  void notifyUserDataChanged() {
    // 这里只需要简单地触发observable状态变化
    // MobX会自动通知所有依赖于currentUser的观察者
    final temp = currentUser;
    currentUser = null;
    currentUser = temp;

    // 同时刷新推荐页面的香水数据
    RootStore().recommendStore.refreshPerfumeData();
  }

  // 打开图片选择器选择头像
  Future<void> pickAvatar(BuildContext context) async {
    // 确保每次调用时没有显示加载提示
    EasyLoading.dismiss();

    try {
      // 直接使用简化的选择方式
      final List<AssetEntity>? entities = await AssetPicker.pickAssets(
        context,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          textDelegate: EnglishAssetPickerTextDelegate(),
          themeColor: Color(0xFFBE88FF),
        ),
      );

      if (entities == null || entities.isEmpty) {
        // 用户取消选择
        print('No image selected');
        return;
      }

      // 显示处理中提示
      EasyLoading.show(status: 'Processing...');

      // 获取选中的图片
      final AssetEntity entity = entities.first;

      try {
        // 直接获取文件
        final File? imageFile = await entity.file;

        if (imageFile == null) {
          EasyLoading.dismiss();
          EasyLoading.showError('Failed to get image file');
          return;
        }

        // 获取文件路径
        final String imagePath = imageFile.path;
        print('Selected image path: $imagePath');

        // 更新用户头像
        final bool success = await updateUserAvatar(imagePath);

        EasyLoading.dismiss();
        if (success) {
          EasyLoading.showSuccess('Avatar updated successfully');
        } else {
          EasyLoading.showError('Failed to update avatar');
        }
      } catch (fileError) {
        EasyLoading.dismiss();
        print('Error processing image file: $fileError');
        EasyLoading.showError('Failed to process image');
      }
    } catch (e) {
      EasyLoading.dismiss();
      print('Error in image picker: $e');
      EasyLoading.showError('Failed to open photo gallery');
    }
  }

  // 处理设置项点击
  void handleSettingItemClick(BuildContext context, String title) {
    switch (title) {
      case 'Modify signature':
        // 显示修改个人描述对话框
        _showDescriptionEditDialog(context);
        break;
      case 'Privacy Policy':
        // 跳转到隐私政策页面
        context.push('/privacy-policy');
        break;
      case 'Terms Of service':
        // 跳转到服务条款页面
        context.push('/terms-of-service');
        break;
      case 'Eula':
        // 跳转到规则页面
        context.push('/rules');
        break;
    }
  }

  // 显示修改个人描述对话框
  void _showDescriptionEditDialog(BuildContext context) {
    // 使用StatefulBuilder来管理TextField控制器
    final initialDescription = currentUser?.description ?? '';

    showDialog(
      context: context,
      barrierDismissible: false, // 禁止点击外部关闭对话框
      builder: (dialogContext) {
        // 在builder内部创建controller，确保其生命周期与对话框一致
        final descriptionController = TextEditingController(
          text: initialDescription,
        );

        return PopScope(
          canPop: true,
          child: Dialog(
            backgroundColor: Colors.transparent,
            elevation: 0,
            child: Container(
              width: 325.w,
              padding: EdgeInsets.all(24.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20.r),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 10,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    'Edit Signature',
                    style: TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w600,
                      color: const Color(0xFF2D1457),
                    ),
                  ),
                  SizedBox(height: 20.h),
                  TextField(
                    controller: descriptionController,
                    decoration: InputDecoration(
                      hintText: 'Enter your signature',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12.r),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12.r),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12.r),
                        borderSide: BorderSide(color: const Color(0xFFA794FD)),
                      ),
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                    ),
                    maxLength: 100,
                    maxLines: 3,
                  ),
                  SizedBox(height: 24.h),
                  Row(
                    children: [
                      Expanded(
                        child: _buildButton(
                          text: 'Cancel',
                          onPressed: () {
                            // 直接关闭对话框，不需要手动处理controller
                            Navigator.of(dialogContext).pop();
                          },
                          color: Colors.grey.shade200,
                          textColor: Colors.black87,
                        ),
                      ),
                      SizedBox(width: 16.w),
                      Expanded(
                        child: _buildButton(
                          text: 'Update',
                          onPressed: () {
                            final newDescription =
                                descriptionController.text.trim();
                            // 先关闭对话框，避免异步操作完成后使用已销毁的controller
                            Navigator.of(dialogContext).pop();

                            // 在对话框关闭后执行更新操作
                            updateUserDescription(newDescription).then((
                              result,
                            ) {
                              // 显示更新成功提示
                              if (result) {
                                EasyLoading.showSuccess(
                                  'Signature updated successfully',
                                );
                              }
                            });
                          },
                          color: const Color(0xFFA794FD),
                          textColor: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  // 构建按钮
  Widget _buildButton({
    required String text,
    required VoidCallback onPressed,
    required Color color,
    required Color textColor,
  }) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        backgroundColor: color,
        foregroundColor: textColor,
        padding: EdgeInsets.symmetric(vertical: 14.h),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(30.r),
        ),
        elevation: 0,
      ),
      child: Text(
        text,
        style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
      ),
    );
  }
}
